<template>
  <div class="test-connection">
    <el-card>
      <div slot="header">
        <span>服务器连接测试</span>
      </div>
      
      <el-alert
        title="根据说明文档，后端服务应运行在 http://localhost:8081"
        type="info"
        show-icon
        style="margin-bottom: 20px;"
      ></el-alert>
      
      <el-form :model="testForm" label-width="120px">
        <el-form-item label="测试端点">
          <el-select v-model="testForm.endpoint" name="endpoint" placeholder="请选择测试端点" aria-label="测试端点" title="测试端点">
            <el-option label="设备列表" value="/device/findAll"></el-option>
            <el-option label="用户列表" value="/selectAllUser"></el-option>
            <el-option label="用户登录" value="/login"></el-option>
            <el-option label="自定义" value="custom"></el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item v-if="testForm.endpoint === 'custom'" label="自定义URL">
          <el-input v-model="testForm.customUrl" name="customUrl" placeholder="请输入测试URL，如: /device/findAll" aria-label="自定义URL" title="自定义URL"></el-input>
        </el-form-item>
        
        <el-form-item v-if="testForm.endpoint === '/login'" label="登录参数">
          <el-input v-model="testForm.username" name="username" placeholder="用户名" style="margin-bottom: 10px;" aria-label="用户名" title="用户名"></el-input>
          <el-input v-model="testForm.password" name="password" placeholder="密码" type="password" aria-label="密码" title="密码"></el-input>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="testConnection" :loading="loading" aria-label="测试连接" title="测试连接">测试连接</el-button>
          <el-button @click="clearLog" aria-label="清空日志" title="清空日志">清空日志</el-button>
        </el-form-item>
      </el-form>
      
      <el-divider></el-divider>
      
      <div class="log-section">
        <h3>测试日志</h3>
        <el-card class="log-container">
          <div v-for="(log, index) in logs" :key="index" :class="['log-item', log.type]">
            [{{ log.time }}] {{ log.message }}
          </div>
        </el-card>
      </div>
    </el-card>
  </div>
</template>

<script>
import request from '@/utils/request'
import qs from 'qs'

export default {
  name: 'TestConnection',
  data() {
    return {
      loading: false,
      logs: [],
      testForm: {
        endpoint: '/device/findAll',
        customUrl: '',
        username: '',
        password: ''
      }
    }
  },
  methods: {
    async testConnection() {
      this.loading = true
      const url = this.testForm.endpoint === 'custom' 
        ? this.testForm.customUrl 
        : this.testForm.endpoint
      
      this.addLog(`开始测试连接: ${url}`, 'info')
      
      try {
        let response
        if (this.testForm.endpoint === '/login') {
          // 特殊处理登录接口
          this.addLog(`发送登录请求到: /api${url}`, 'info')
          response = await request({
            url: url,
            method: 'post',
            data: qs.stringify({
              username: this.testForm.username,
              password: this.testForm.password
            }),
            headers: {
              'Content-Type': 'application/x-www-form-urlencoded'
            }
          })
        } else {
          this.addLog(`发送请求到: /api${url}`, 'info')
          response = await request({
            url: url,
            method: 'get'
          })
        }
        
        this.addLog(`收到响应: ${JSON.stringify(response)}`, 'success')
        this.addLog(`连接测试成功!`, 'success')
      } catch (error) {
        if (error.response) {
          this.addLog(`服务器响应错误: ${error.response.status} - ${JSON.stringify(error.response.data)}`, 'error')
        } else if (error.request) {
          this.addLog(`网络错误或服务器无响应: ${error.message}`, 'error')
        } else {
          this.addLog(`请求配置错误: ${error.message}`, 'error')
        }
      } finally {
        this.loading = false
      }
    },
    
    addLog(message, type = 'info') {
      const time = new Date().toLocaleTimeString()
      this.logs.push({
        time,
        message,
        type
      })
      
      // 滚动到底部
      this.$nextTick(() => {
        const container = document.querySelector('.log-container .el-card__body')
        if (container) {
          container.scrollTop = container.scrollHeight
        }
      })
    },
    
    clearLog() {
      this.logs = []
    }
  }
}
</script>

<style scoped>
.test-connection {
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
  /* Add vendor prefixes for better cross-browser compatibility */
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
  width: -webkit-fill-available;
  width: stretch;
}

.log-section {
  margin-top: 30px;
  /* Add vendor prefixes for better cross-browser compatibility */
  -webkit-user-select: text;
  -moz-user-select: text;
  -ms-user-select: text;
  user-select: text;
}

.log-container {
  max-height: 400px;
  overflow-y: auto;
  /* Add vendor prefixes for better cross-browser compatibility */
  -webkit-user-select: text;
  -moz-user-select: text;
  -ms-user-select: text;
  user-select: text;
}

.log-item {
  padding: 5px 0;
  border-bottom: 1px solid #eee;
  font-family: monospace;
  white-space: pre-wrap;
  /* Add vendor prefixes for better cross-browser compatibility */
  -webkit-user-select: text;
  -moz-user-select: text;
  -ms-user-select: text;
  user-select: text;
}

.log-item.info {
  color: #409EFF;
}

.log-item.success {
  color: #67C23A;
}

.log-item.error {
  color: #F56C6C;
}
</style>